package com.hotlcc.bark.common.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hotlcc.bark.common.constant.CommonConstant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class TraceUtil {
    private static final String TRACE_ID_KEY = CommonConstant.LOG_MDC.TRACE_ID;

    public static String put(String traceId) {
        if (StrUtil.isBlank(traceId)) {
            traceId = IdUtil.simpleUUID();
        }
        MDC.put(TRACE_ID_KEY, traceId);
        return traceId;
    }

    public static String get() {
        String traceId = MDC.get(TRACE_ID_KEY);
        if (StrUtil.isBlank(traceId)) {
            traceId = IdUtil.simpleUUID();
            MDC.put(TRACE_ID_KEY, traceId);
        }
        return traceId;
    }

    public static String remove() {
        String traceId = MDC.get(TRACE_ID_KEY);
        MDC.remove(TRACE_ID_KEY);
        return traceId;
    }

    public static String startTrace() {
        try {
            return put(get());
        } catch (Exception e) {
            log.error("TraceUtil#startTrace,error");
            return null;
        }
    }
}
